package com.jindreamit.m3u8.download.runnable;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jindreamit.m3u8.download.util.DownloadUtils;
import com.jindreamit.m3u8.download.util.RedisUtils;

import java.util.LinkedList;
import java.util.List;

public class DownloadRunnable implements Runnable{

    static final public List<DownloadRunnable> errorList=new LinkedList<>();

    private String dirPath;

    private String url;

    private String fileName;

    public DownloadRunnable(String dirPath, String url, String fileName) {
        this.dirPath = dirPath;
        this.url = url;
        this.fileName = fileName;
    }



    @Override
    public void run() {
        try {
            DownloadUtils.download(this.dirPath,this.url,this.fileName);
            System.out.println("线程 "+Thread.currentThread().getId()+" 下载 "+this.fileName+" 完毕");

        }catch (Exception e){
            e.printStackTrace();
            synchronized (errorList){
                errorList.add(this);
            }
        }
    }

    public String getDirPath() {
        return dirPath;
    }

    public void setDirPath(String dirPath) {
        this.dirPath = dirPath;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    public String getFileName() {
        return fileName;
    }

    public void setFileName(String fileName) {
        this.fileName = fileName;
    }

    @Override
    protected void finalize() throws Throwable {
        super.finalize();
        JSONArray jsonArray=new JSONArray();
        jsonArray.addAll(errorList);
        RedisUtils.append("fail_download", jsonArray.toJSONString());
    }
}
